<?php 

namespace IMT\ServicesBundle\Controller;

use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\View\View;

class EventRestController extends Controller
{
	/**
	 * GET /event/{eventId}
	 *
	 * @param string $eventId
	 * @return Response
	 */
	public function getEventAction($eventId)
	{
			
			if(intval($eventId) == 0)
	    		throw new \SoapFault('ID_NOT_VALID', 'L\'id est incorrect : '.$eventId);
	    	
	    	// Authentification du user
	    	$userManager = $this->get('fos_user.user_manager');
	    	$user = $userManager->findUserBy(array('username' => 'admin'));
	    	
	    	$encoder_service = $this->get('security.encoder_factory');
	    	$encoder = $encoder_service->getEncoder($user);
	    	$encoded_pass = $encoder->encodePassword('azerazer', $user->getSalt());
	    	
	    	if (!$user)
	    		throw new \SoapFault('USER_NOT_FOUND', 'L\'identifiant ou le mot de passe du compte utilisateur est incorrect');
	    	else if($user->getPassword() != $encoded_pass)
	    		throw new \SoapFault('USER_NOT_FOUND', 'L\'identifiant ou le mot de passe du compte utilisateur est incorrect');
	    	
	    	//$this->authenticateUser($user);
	    	$providerKey = $this->container->getParameter('fos_user.firewall_name');
	    	$token = new UsernamePasswordToken($user, null, $providerKey, $user->getRoles());
	    	
	    	$this->container->get('security.context')->setToken($token);
	    	
	    	// Récupération de l'event
	    	$repository = $this->getDoctrine()->getRepository('IMTEventBundle:Event');
    		$event = $repository->findOneById($eventId);
    		
    		if (!$event)
    			throw new \SoapFault('EVENT_NOT_FOUND', 'L\'event ayant l\'id '.$eventId.' n\'existe pas');
    		
    		
    		// Vérification des droits d'acces
    		$securityContext = $this->get('security.context');
    		
    		if(false === $securityContext->isGranted('VIEW', $event)){
    			throw new \SoapFault('EVENT_ACCESS_DENIED', 'Acces refuse pour '.$user->getUsername());
    		}

		$view = View::create()
		->setStatusCode(200)
		->setData($event);

		return $this->get('fos_rest.view_handler')->handle($view);
	}
}